import { _decorator, Component, EventTouch, Input, input, instantiate, Node, Prefab, Vec3 } from 'cc';
import { Bullet } from './Bullet';
const { ccclass, property } = _decorator;

enum ShootType {
    OneShoot,
    TwoShoot
};

@ccclass('Player')
export class Player extends Component {

    @property
    shootRate: number = 0.5;
    @property(Node)
    bulletParent: Node = null;

    @property(Prefab)
    bullet1Prefab: Prefab = null;

    @property(Node)
    position1: Node = null;


    @property(Prefab)
    bullet2Prefab: Prefab = null;
    @property(Node)
    position2: Node = null;
    @property(Node)
    position3: Node = null;

    @property
    shootType: ShootType = ShootType.OneShoot;

    shootTimer: number = 0;

    protected onLoad() {
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);

    }
    start() {

    }

    update(deltaTime: number) {

        switch (this.shootType) {
            case ShootType.OneShoot:
                this.oneShoot(deltaTime);
                break;
            case ShootType.TwoShoot:
                this.twoShoot(deltaTime);
                break;

        }


    }

    oneShoot(deltaTime: number) {

        this.shootTimer += deltaTime;
        if (this.shootTimer > this.shootRate) {
            this.shootTimer = 0;
            const bullet1 = instantiate(this.bullet1Prefab);
            this.bulletParent.addChild(bullet1);
            bullet1.setWorldPosition(this.position1.worldPosition);
        }
    }


    twoShoot(deltaTime: number) {

        this.shootTimer += deltaTime;
        if (this.shootTimer > this.shootRate) {
            this.shootTimer = 0;
            const bullet1 = instantiate(this.bullet2Prefab);
            const bullet2 = instantiate(this.bullet2Prefab);
            this.bulletParent.addChild(bullet1);
            this.bulletParent.addChild(bullet2);
            bullet1.setWorldPosition(this.position2.worldPosition);
            bullet2.setWorldPosition(this.position3.worldPosition);
        }
    }


    protected onDestroy(): void {
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);

    }
    onTouchMove(event: EventTouch) {
        const width = 480;
        const height = 852;

        const p = this.node.position;
        let targetPosition = new Vec3(p.x + event.getDeltaX(), p.y + event.getDeltaY(), p.z);
        //this.node.setPosition(p.x + event.getDeltaX(), p.y + event.getDeltaY(), p.z);
        if (targetPosition.x > width / 2) {
            targetPosition.x = width / 2;
        }
        else if (targetPosition.x < - width / 2) {
            targetPosition.x = -width / 2;
        }

        if (targetPosition.y > height / 2) {
            targetPosition.y = height / 2;
        }
        else if (targetPosition.y < - height / 2) {
            targetPosition.y = -height / 2;
        }


        this.node.setPosition(targetPosition);

    }
}


